<?php

class PXFValidatorItem
{
	protected $error_msg = 'VALIDATOR_DEFAULT_ERROR';
	protected $key; 
	protected $required;
	protected $value;
	protected $isset;
	protected $args = array();

	public function  __construct( $key,$required,$args = array())
	{
		$this->key = $key;
		$this->args = $args;
		$this->value = isset($_REQUEST[$key]) ? $_REQUEST[$key] : null;
		$this->required = $required;
		$this->isset = !($this->value === null) && (strlen($this->value) > 0);
	}

	public function validate()
	{
		return $this->required ? ($this->isset && strlen($this->value) > 0) :  true;
	}

	public function getKey()
	{
		return $this->key;
	}

	public function getErrorMsg()
	{
		return $this->error_msg;
	}

	public function setErrorMsg($msg)
	{
		$this->error_msg = $msg;
	}

	function getValue()
	{
		return $this->value;
	}
}

class PXFValidator
{
	private $validators = array();

	private function __construct()
	{
	}

	public function getNew()
	{
		return new PXFValidator();
	}
	
	public function addItem(& $validator)
	{
		array_push($this->validators,$validator);	
	}

	public function validate()
	{
		$errors = array();
		foreach($this->validators as $validator)
		{
			if(!$validator->validate())
			{
				$errors[$validator->getKey()] = PXFLang::get($validator->getErrorMsg(),'validator_module');
			}
		}
		return $errors;
	}
} 

class ValidatorVoid extends PXFValidatorItem
{
	function validate()
	{
		return true;
	}
}

class ValidatorInArray extends PXFValidatorItem 
{
	function validate()	
	{
		if($this->required && (!$this->isset))
		{
			return false;
		}
		else
		{
			if($this->isset)
				return (in_array($this->value,$this->args)); 
			else {return true;}
		}
	}
}

class ValidatorImageFile extends  PXFValidatorItem 
{
	var $content;
	
	public function validate()
	{			
		if(isset($_FILES[$this->key]) && $_FILES[$this->key]['size'] > 0 && in_array($_FILES[$this->key]['type'],$this->args))
		{			
			return true;
		}		
		return false;
	}
	
	public function getValue()
	{					
		if(isset($_FILES[$this->key]) && $_FILES[$this->key]['size'] > 0 && in_array($_FILES[$this->key]['type'],$this->args))
		{			
			return $_FILES[$this->key];
		}
		return null;
	}	
	
}

class ValidatorEmail extends PXFValidatorItem
{
	public function validate()
	{
		if($this->required && (!$this->isset)) { return false;}
		else
		{
			if($this->isset)
				return (eregi("^[a-z]+[a-z0-9_-]*(([.]{1})|([a-z0-9_-]*))[a-z0-9_-]+[@]{1}[a-z0-9_-]+[.](([a-z]{2,3})|([a-z]{3}[.]{1}[a-z]{2}))$",$this->value)); 
			else {return true;}
		}
	}
}

class ValidatorSimpleText extends PXFValidatorItem
{
	public function validate()
	{		
		if(!array_key_exists('min',$this->args)) $this->args['min'] = 1;
		if(!array_key_exists('max',$this->args)) $this->args['max'] = 250;
		$len = $this->isset ? strlen(trim($this->value)) : 0;
		return $this->required ? 
					($this->isset && ($this->args['min'] <= $len) && ($len <= $this->args['max'])) :
					true;
	}
}

?>
